from django.shortcuts import render
from rest_framework.views import APIView, Response,status

from oauth.exceptions import QQAPIError
from oauth.models import OAuthQQUser
from oauth.utils import OAuthQQ


# Create your views here.

# url(r'^qq/authorization/$',views.QQAuthURLView.as_view())

class QQAuthorURLView(APIView):
    """
    QQ登陆的url地址

    """

    def get(self, request):
        next = request.query_params.get('next', '/')

        # 获取qq 登陆的地址
        oauth = OAuthQQ(state=next)

        login_url = oauth.get_login_url()

        # 给客户端返回 login_url
        return Response({'login_url': login_url})


class QQAuthUserView(APIView):

    def get(self,request):
        """
        获取QQ登陆用户的openid并处理
        1,获取code 并校验(code必传)
        2,获取QQ登陆用户openid
            2.1 根据code请求qq服务器获取access_token
            2.2  根据access_token 请求QQ服务器获取openid
        3, 根据openid 判断是否绑定过本网站用户
            3.1 如果已绑定,这接生成jwt token并返回
            3.2 如果未绑定,将openid 加密并返回
        """

        # 获取QQ登陆用户的openid并处理
        code = request.query_params.get('code')

        # 1,获取code 并校验(code必传)
        if code is None:
            return Response({'message':'缺少code参数'},status=status.HTTP_400_BAD_REQUEST)

        # 2,获取QQ登陆用户openid
        oauth = OAuthQQ()

        try:
            # 2.1 根据code请求qq服务器获取access_token
            access_token = oauth.get_access_token(code)

            # 2.2  根据access_token 请求QQ服务器获取openid
            openid = oauth.get_openid(access_token)
        except QQAPIError:
            return Response({'message':'QQ登陆异常'},status=status.HTTP_503_SERVICE_UNAVAILABLE)

            # 3, 根据openid 判断是否绑定过本网站用户
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:

            # 3.1 3.2 如果未绑定，将openid加密并返回
            secret_openid = oauth.generate_save_user_token(openid)
            return Response({'access_token':secret_openid})

        else:

            # 3.1 如果已绑定，直接生成jwt token并返回
            from rest_framework_jwt.settings import api_settings

            user = qq_user.user
            # 生成载荷的内容
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            # 生成jwt token
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            # 返回响应
            response_data = {
                'user_id':user.id,
                'username':user.username,
                'token':token
            }
            return Response(response_data)